package cn.unknowpupil.init.controller.common;

import cn.unknowpupil.init.common.constant.SecurityConstants;
import cn.unknowpupil.init.utils.FileUtils;
import cn.unknowpupil.init.utils.StringUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created at 2020/11/2 by w10g <br>
 * Initialize CommonController ... <br>
 *
 * @author unknowpupil
 * @since 0.0.1
 */
@Api(tags = {"系统-公共模块"}, value = "Common")
@RestController
@RequestMapping("common")
@Slf4j
public class CommonController {

    @ApiOperation("公共：下载")
    @GetMapping("download")
    public void remove(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) {
        try {
            if (!FileUtils.isValidFilename(fileName)) {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = SecurityConstants.DOWNLOAD_PATH + fileName;

            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, realFileName));
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete) {
                FileUtils.deleteFile(filePath);
            }
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

}
